process.title="yunxiaoxin_im";
import  express from 'express';
import https from 'https';
import SocketIO from 'socket.io';
import compression from 'compression';
//import {validNick, findIndex, sanitizeString} from './util';
import settings from './app/config'

let _ = require("lodash"),
  path = require("path"),
  fs = require("fs"),
  all = require('require-tree'),
  redis = require('redis'),
  models = all(path.resolve('./app/models')),
  controllers = all(path.resolve('./app/controllers')),
  Service = require('./app/service/index')
  
let app = express();
let httpsoptions = {
        key: fs.readFileSync(settings.https.key),
        cert: fs.readFileSync(settings.https.cert),
        passphrase: settings.https.passphrase
};
let server = https.createServer(httpsoptions,app);
let logger = require('morgan');
let io = new SocketIO(server);

let socket_redis = require('socket.io-redis');
io.adapter(socket_redis(
    {
    host:settings.redis.host,
    port:settings.redis.port,
    db : settings.redis.cachedb,
    password : settings.redis.password,
    prefix : 'so'
    }
)); //需要指定db
let ioauth = require('socketio-auth')
let jwt = require('jsonwebtoken')

/**
 * 能够放到controller里面的，包括io，socket，log，db
 * 这块学习glue代码
 * 
 * 充分利用emit的callback函数，可以模拟req/res模式
 */

app.use(compression({}));
app.use(logger('dev'));

Service.authManager.auth(data)
let authenticate = (socket, data, callback)=>{
    //Service.authManager.auth(data)

    let token = data.token 
    let decoded = jwt.verify(token ,settings.secrets.jwt);
    let uid = decoded.uid;
    Service.userManager.getUserByUid(uid).then(function(user){
        user.id = uid;
        console.log(user)
        if (!user) { return done(null, false); }
        return callback(null, true);
    },()=>{
        return callback(new Error("User not found"));
    })

    /*
    db.findUser('User', {username:username}, function(err, user) {

      //inform the callback of auth success/failure
      if (err || !user) return callback(new Error("User not found"));
      return callback(null, user.password == password);
    });*/
}
let  postAuthenticate= (socket, data)=> {
  let token = data.token 
  let decoded = jwt.verify(token ,settings.secrets.jwt);
  let uid = decoded.uid;
  Service.userManager.getUserByUid(uid).then(function(user){
    user.id = uid;
    socket.client.user = user;
    socket.emit("connected",'welcome to the chat server')
    _.each(controllers,(controller)=>{
        controller.apply({
            app : app,
            service : service ,
            settings : settings,
            models : models,
            logger : logger,
            socket : socket,
            io : io 
        })
    })
  });
}
let disconnect= (socket) =>{
  console.log(socket.id + ' disconnected');
  socket.broadcast.emit('userDisconnect', {});
}
ioauth(io, {
  authenticate: authenticate,
  postAuthenticate: postAuthenticate,
  disconnect: disconnect,
  timeout: 1000
});

models.sequelize.sync().then(()=>{
    let port = settings.https.enable && settings.https.port;
    server.listen(port,()=>{
        console.log('yunxiaoxin chat server start',)
    })
})

